/**
 *    Copyright 2009 Thomas Johnson
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.weareriot.hitprox;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;

public class Runner {
	private static final long START_TIMEOUT = 10000L;
	
	public static void main(String[] args) {
		final HitProxUI ui = new HitProxUI();
		
		final Server server = new Server(8888);
		
		final Context root = new Context(server, "/", Context.SESSIONS);
		root.addServlet(new ServletHolder(new HitboxSnooperProxyServlet(ui)), "/*");
		Connector[] connectors = server.getConnectors();
		System.out.println("The server has " + connectors.length + " connectors");
		for(int i = 0; i < connectors.length; i++) {
			Connector connector = connectors[i];
			System.out.println(i + ": " + connector);
			// Temporary workaround for:
			//    http://jira.codehaus.org/browse/JETTY-336
			//    http://jira.codehaus.org/browse/JETTY-65
			// Based on http://markmail.org/message/u6ofq2dvm2f67fat
			int origBufferSize = connector.getHeaderBufferSize();
			int desiredMinimum = 16 * 1024; // 16 KB as two 4KB headers are expected 
			connector.setHeaderBufferSize(Math.max(origBufferSize, desiredMinimum));
		}
		
		try {
			server.start();
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
		
		
		final long start = System.currentTimeMillis();
		final long deadline = start + START_TIMEOUT;
		
		while(System.currentTimeMillis() <= deadline && !server.isRunning()
				&& !server.isFailed() && !server.isStopped() && !server.isStopping()) {
			try {
				Thread.sleep(500);
			} catch(InterruptedException e) {
				// Swallow exception
			}
		}
		
		JFrame window = new JFrame("HitProx");
		window.setPreferredSize(new Dimension(600, 800));
		window.add(ui, BorderLayout.CENTER);
		window.pack();
		
		window.setVisible(true);
		
		window.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent we) {
				super.windowClosing(we);
				try {
					server.stop();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
}
